package cn.ven.controller;

import cn.ven.entity.MyUser;
import cn.ven.service.UserService;
import cn.ven.tool.RespJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
   管理员进行用户操作
   身份权限"P"才能访问
 */
@Controller
@RequestMapping("/api/adm/user")
public class AdmUserController {
    private static Logger log = LoggerFactory.getLogger(AdmUserController.class);
    @Autowired
    UserService userService;

    //查找所有的用户
    @RequestMapping("/findAll/{start}/{num}")
    @ResponseBody
    public Map<String,Object> findAll(@PathVariable("start")Integer start,
                                      @PathVariable("num")Integer num){
        List<MyUser> users = userService.findAll(start - 1, num);//按分页查找所有的用户
        log.info("users==="+users);
        Map<String,Object> info =new HashMap<>(); //用于返回给前端的集合，查询数据和数据总条数
        info.put("users",users);
        info.put("total",userService.getCount()); //数据总台条数
        return RespJson.pack(200,"",info);
    }

    //创建管理员
    @RequestMapping("/addAdm")
    @ResponseBody
    public Map<String,Object> addAdm(@RequestBody MyUser user){ //前端走json
        userService.addAdm(user); //添加用户
        return RespJson.pack(200,"添加管理员成功",user);
    }

    //根据用户id重置密码，重置密码会把账户冻结
    @RequestMapping("/resetPwd/{uid}")
    @ResponseBody
    public Map<String,Object> resetPwd(@PathVariable("uid")Integer uid){
        log.info("uid==="+uid);
        MyUser user = userService.findById(uid); //先查找用户
        if (user==null){ //当用户不存在的时候
            return RespJson.pack(401,"用户不存在","");
        }
        userService.resetPwd(user);//重置用户密码
        return RespJson.pack(200,"冻结成功","");
    }

    //解冻某个账号
    @RequestMapping("/close/{uid}")
    @ResponseBody
    public Map<String,Object> closeUser(@PathVariable("uid")Integer uid){
        MyUser user = userService.findById(uid); //先查找用户
        if (user==null){ //用户不存在的时候
            return RespJson.pack(401,"用户不存在","");
        }
        userService.closedAccount(user);
        return RespJson.pack(200,"解冻成功","");
    }

    //根据id查找用户
    @RequestMapping("/findById/{uid}")
    @ResponseBody
    public Map<String,Object> findById(@PathVariable("uid")Integer uid){
        MyUser user = userService.findById(uid); //根据用户id查找用户
        if (user==null){ //用户不存在的时候
            return RespJson.pack(500,"该用户不存在","");
        }
        return RespJson.pack(200,"",user);
    }





}
